package com.itheima.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.constant.TokenConstant;
import com.itheima.pojo.User;
import com.itheima.properties.SMSProperties;
import com.itheima.service.UserService;
import com.itheima.utils.SMSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author 小帅蓝
 * @Date 2022/6/23 17:22
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @Resource
    private SMSProperties smsProperties;

    @Resource
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody SendMsgDTO sendMsgDTO) {
        //发送验证码，先手动生成验证码
        String code = RandomUtil.randomNumbers(4);
        log.info("验证码：" + code);
        //发送验证码
        SMSUtil.sendSMS(smsProperties.getAccessKeyId(),
                smsProperties.getAccessKeySecret(),
                smsProperties.getSignName(),
                smsProperties.getTemplateCode(),
                sendMsgDTO.getPhone(), code);
        //将验证码存到redis
        redisTemplate.opsForValue().set(sendMsgDTO.getPhone(), code, 60 * 60 * 24 * 7, TimeUnit.SECONDS);

        return R.success("手机验证码短信发送成功");
    }

    @PostMapping("/login")
    public R<LoginVO> login(@RequestBody LoginDTO dto) {
        String phone = dto.getPhone();
        String code = dto.getCode();

        //判断当前手机号在user表中存不存在，不存在添加
        User user = userService.queryByPhone(phone);
        if (ObjectUtil.isNull(user)) {
            //插入当前数据到user表
            user = new User();
            user.setPhone(phone);
            user.setId(new Snowflake().nextIdStr());
            userService.addUser(user);
        }

        if (StrUtil.isEmpty(code)) {
            return R.error("请输入验证码");
        }
        //用phone作为key在redis中查找code
        String codeTrue = (String) redisTemplate.opsForValue().get(phone);
        //判断codeTrue是否为空
        if (!code.equals(codeTrue)) {
            return R.error("验证码错误");
        }

        user = userService.queryByPhone(phone);
        //生成token，将user存放到redis
        String token = System.currentTimeMillis() + user.getId();
        token = DigestUtils.md5DigestAsHex(token.getBytes());
        redisTemplate.opsForValue().set(TokenConstant.USER_TOKEN_PREFIX + token, JSON.toJSONString(user), 60 * 60, TimeUnit.SECONDS);
        log.info(String.valueOf(redisTemplate.getKeySerializer()));

        //返回数据
        LoginVO loginVO = new LoginVO();
        BeanUtil.copyProperties(user, loginVO);
        loginVO.setToken(token);
        return R.success(loginVO);
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request) {
        //使用request获取请求头的token
        String token = request.getHeader("AuthorizationUser");
        //删除redis中的token
        redisTemplate.delete(TokenConstant.USER_TOKEN_PREFIX + token);
        return R.success("退出成功");
    }
}
